package com.ruoyi.handler;

/**
 * @Author: TT
 * @Date: 2025/8/27 17:31
 * @Description: 组数自动映射字串
 * @Version: v1.0
 */

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.VARCHAR) // 处理 JDBC VARCHAR 类型
@MappedTypes(String[].class)       // 映射到 Java String[] 类型
public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {
    // 定义分隔符
    private static final String DELIMITER = ",";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        // 将 String[] 转换为逗号分隔的 String 并存入数据库
        String joinedString = String.join(DELIMITER, parameter);
        ps.setString(i, joinedString);
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String sqlString = rs.getString(columnName);
        return (sqlString != null && !sqlString.isEmpty()) ? sqlString.split(DELIMITER) : new String[0];
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String sqlString = rs.getString(columnIndex);
        return (sqlString != null && !sqlString.isEmpty()) ? sqlString.split(DELIMITER) : new String[0];
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String sqlString = cs.getString(columnIndex);
        return (sqlString != null && !sqlString.isEmpty()) ? sqlString.split(DELIMITER) : new String[0];
    }
}